package com.feihong.txgw.ui.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dtr.settingview.lib.SettingView;
import com.dtr.settingview.lib.entity.SettingData;
import com.dtr.settingview.lib.entity.SettingViewItemData;
import com.dtr.settingview.lib.item.BasicItemViewH;
import com.feihong.txgw.R;
import com.feihong.txgw.dialog.ZCodeDialog;
import com.feihong.txgw.ui.activity.HomeActivity;
import com.feihong.txgw.ui.activity.integral.BackIntegralActivity;
import com.feihong.txgw.ui.activity.integral.IntegralDetailActivity;
import com.feihong.txgw.ui.activity.integral.InviteFriendsActivity;
import com.feihong.txgw.ui.activity.order.MyOrderActivity;
import com.feihong.txgw.ui.activity.setting.ServiceMessageActivity;
import com.feihong.txgw.ui.activity.user.LoginActivity;
import com.feihong.txgw.ui.activity.user.MyDeliveryAdrActivity;
import com.feihong.txgw.ui.activity.user.SannerActivity;
import com.feihong.txgw.ui.activity.user.ShareActivity;
import com.feihong.txgw.ui.activity.user.UserInfoEditeActivity;
import com.feihong.txgw.ui.fragment.base.BaseFragment;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.json.user.MyPointInfo;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.RefreshMsgIconMessage;
import com.feihong.txgw.utils.EventBusUtil;
import com.feihong.txgw.utils.ScreenUtil;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.glidehttps.GlideOptionsSetting;
import com.feihong.txgw.utils.helper.RxHelper;
import com.feihong.txgw.utils.manage.RetrofitManager;
import com.feihong.txgw.utils.manage.ThreadPoolManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import q.rorbin.badgeview.Badge;

import static com.feihong.txgw.utils.UserLoginInfo.getUserInfo;

/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 * 我的Fragment  Tab3
 */

public class UserFragment extends BaseFragment {

    @BindView(R.id.user_photo)
    RelativeLayout userPhoto;  // 用户头像
    @BindView(R.id.tv_log)
    TextView tvLog;            // 登录按钮
    @BindView(R.id.tv_allorder)
    TextView tvAllorder;       // 全部订单
    @BindView(R.id.tv_dfk)
    TextView tvDfk;            // 待付款
    @BindView(R.id.tv_dsh)
    TextView tvDsh;            // 待收货
    @BindView(R.id.tv_dpj)
    TextView tvDpj;            // 待评价
    @BindView(R.id.tv_shouhou)
    TextView tvShouhou;        // 售后
    @BindView(R.id.tv_jfnum)
    TextView tvJfnum;          // 积分明细数
    @BindView(R.id.ll_jfmx)
    LinearLayout llJfmx;       // 积分明细
    @BindView(R.id.tv_dfnum)
    TextView tvDfnum;          // 待返积分数
    @BindView(R.id.ll_jfdf)
    LinearLayout llJfdf;       // 待返积分
    @BindView(R.id.tv_hynum)
    TextView tvHynum;          // 邀请好友数
    @BindView(R.id.ll_yqhy)
    LinearLayout llYqhy;       // 邀请好友
    @BindView(R.id.user_setview)
    SettingView userSetview;
    @BindView(R.id.img_btn_message)
    ImageButton imgBtnMessage;
    @BindView(R.id.img_btn_setting)
    ImageButton imgBtnSetting;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.underline)
    View underline;
    @BindView(R.id.person_z_code)
    ImageView mZCode;
    @BindView(R.id.user_photo_setting)
    ImageView userPhotoSetting;
    private String userId;

    private RefreshToken mRefreshTokenManager;

    private RequestOptions mGlideOptions;
    private int mShareMsgWhat = 10;
    private int mZcodMsgWhat = 11;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == mShareMsgWhat) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ShareActivity.class);
                if (isUserLogin()) {
                    intent.putExtra(ShareActivity.IS_LOGING, ShareActivity.LOGIN);
                } else {
                    intent.putExtra(ShareActivity.IS_LOGING, ShareActivity.LOGOUT);
                }
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.alpha_in,R.anim.alpha_out);
            } else if (msg.what == mZcodMsgWhat) {
                mZCodeDialog = new ZCodeDialog(getActivity());
                mZCodeDialog.show();
            }
        }
    };

    public static UserFragment newInstance(String tabName) {
        UserFragment userFragment = new UserFragment();
        userFragment.tag = tabName;
        return userFragment;
    }

    @Override
    public void setTheme() {
    }

    @Override
    public int setLayoutID() {
        return R.layout.fragment_user;
    }
    @Override
    public void onSupportVisible() {
//        setSpecificTitleLayout(mStatusView);
        super.onSupportVisible();
//        mImmersionBar.statusBarDarkFont(true).statusBarColor(R.color.white).init();
    }
    //判断当前页面是否显示
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        // hidden == true 说明当前的页面隐藏掉了， false 说明 当前的页面显示了
        if (!hidden) {
            if (((HomeActivity) _mActivity).isHaveNewMsg) {
                imgBtnMessage.setImageResource(R.mipmap.unread_msg);
            } else {
                imgBtnMessage.setImageResource(R.mipmap.message_normal_icon);
            }
            bindUserData();
        }
    }

    private void bindUserData() {
        if (UserLoginInfo.isUserLogin()) {
            //用户已经登录。
            getNetData();
            if (getUserInfo().getUserName().startsWith("tx100_") || getUserInfo().getUserName().isEmpty()) {
                tvLog.setText(UserLoginInfo.getUserPhone());
            } else {
                tvLog.setText(getUserInfo().getUserName());
            }
        } else {
            //用户没有登录
            tvLog.setEnabled(true);
            tvLog.setText("登录/注册");
        }
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        //页面显示才能触发
        //绑定View

        initView();

        //绑定数据
        bindData();
    }

    @Override
    public void onUserLogin(LoginMessage message) {
        switch (message.getAction()) {
            case LoginMessage.ACTION_LOGIN:
                if (!UserLoginInfo.getUserInfo().getUserPic().isEmpty()) {
                    //头像显示
                    Glide.with(_mActivity).load(UserLoginInfo.getUserInfo().getUserPic()).apply(GlideOptionsSetting.getDefaultOptions(R.mipmap.user_head,R.mipmap.user_head)).into(userPhotoSetting);
                }

                if (getUserInfo().getUserName().startsWith("tx100_") || getUserInfo().getUserName().isEmpty()) {
                    tvLog.setText(UserLoginInfo.getUserPhone());
                } else {
                    tvLog.setText(getUserInfo().getUserName());
                }

                break;
            case LoginMessage.ACTION_CANCEL:
                tvLog.setEnabled(true);
                tvLog.setText("登录/注册");
                Glide.with(_mActivity).load(R.mipmap.user_head).apply(GlideOptionsSetting.getDefaultOptions(R.mipmap.user_head,R.mipmap.user_head)).into(userPhotoSetting);
                break;
            case LoginMessage.ACTION_EXIT:
                tvLog.setEnabled(true);
                tvLog.setText("登录/注册");
                Glide.with(_mActivity).load(R.mipmap.user_head).apply(GlideOptionsSetting.getDefaultOptions(R.mipmap.user_head,R.mipmap.user_head)).into(userPhotoSetting);
                break;
            default:
                tvLog.setEnabled(true);
                tvLog.setText("登录/注册");
                Glide.with(_mActivity).load(R.mipmap.user_head).apply(GlideOptionsSetting.getDefaultOptions(R.mipmap.user_head,R.mipmap.user_head)).into(userPhotoSetting);
                break;
        }

        if (isUserLogin()) {
            getNetData();
        } else {
            tvJfnum.setText("0");
            tvDfnum.setText("0");
            tvHynum.setText("0");
        }
    }

    private SettingData mItemData = null;
    private SettingViewItemData mItemViewData = null;
    private List<SettingViewItemData> mListData = new ArrayList<SettingViewItemData>();
    private Badge dfk, dsh, dpj;

    @Override
    public void initView() {

        EventBusUtil.register(this);
        mRefreshTokenManager = RefreshToken.getInstance();

        imgBtnSetting.setVisibility(View.VISIBLE);
        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("我的地址");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        mItemData.setSubTitle("地址添加、修改");
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.user_address));

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("扫一扫");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        mItemData.setSubTitle("邀请好友");
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.user_sys));
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("专属客服");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        mItemData.setSubTitle("投诉、咨询");
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.user_zskf));
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("分享");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        mItemData.setSubTitle("分享给好友");
        mItemData.setDrawable(getResources().getDrawable(R.mipmap.share_icon));

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        userSetview.setAdapter(mListData);


        // settingview的点击事件
        userSetview.setOnSettingViewItemClickListener(new SettingView.onSettingViewItemClickListener() {
            @Override
            public void onItemClick(int index) {
                if(isFastDoubleClick(SettinglastClickTime)){
                    return;
                }
                SettinglastClickTime = System.currentTimeMillis();
                switch (index) {
                    case 0:
                        //收货地址
                        Intent intent = new Intent(getContext(), MyDeliveryAdrActivity.class);
                        checkLoginAndStartIntent(intent);
                        break;
                    case 1:
                        //扫一扫
                        Intent intentscan = new Intent();
                        intentscan.setClass(_mActivity, SannerActivity.class);
                        checkLoginAndStartIntent(intentscan);
                        break;
                    case 2:
                        //客服系统
                        intent = new Intent();
                        intent.setClass(_mActivity, ServiceMessageActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        //分享  弹窗
                        ThreadPoolManager.getInstance().execute(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshTokenManager.RetrofitRefreshTokenForGet();
                                Message message = Message.obtain();
                                message.what = mShareMsgWhat;
                                mHandler.sendMessage(message);
                            }
                        });
                        break;
                    default:break;
                }
            }
        });
    }

    @Override
    public void bindData() {
        txtTitle.setText("我的");
        //   underline.setVisibility(View.GONE);

        mGlideOptions = new RequestOptions()
                .error(R.mipmap.user_head)
                .placeholder(R.mipmap.user_head);
        mZCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserLoginInfo.isUserLogin()) {
                    ThreadPoolManager.getInstance().execute(new Runnable() {
                        @Override
                        public void run() {
                            boolean result = RefreshToken.getInstance().RetrofitRefreshTokenForGet();
                            if (result) {
                                Message message = Message.obtain();
                                message.what = mZcodMsgWhat;
                                mHandler.sendMessage(message);
                            }
                        }
                    });
                } else {
                    showLoginDialog();
                }
            }
        });

        if (UserLoginInfo.isUserLogin()) {
            //头像显示
            if (!UserLoginInfo.getUserInfo().getUserPic().isEmpty()) {
                //头像显示
                Glide.with(_mActivity).load(UserLoginInfo.getUserInfo().getUserPic()).apply(GlideOptionsSetting.getDefaultOptions(R.mipmap.user_head,R.mipmap.user_head)).into(userPhotoSetting);
            }
        }

//        App.getApp().refreshToken();
    }

    private void getNetData() {

        RetrofitManager.getInstance().getPointCount(new HashMap<String, String>()).compose(RxHelper.<String>rxSchedulerHelper())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String result) {

                        String daifan = "";
                        String jifenmingxi = "";
                        int haoyou = 0;

                        tvJfnum.setText(jifenmingxi + "");
                        tvDfnum.setText(daifan + "");
                        tvHynum.setText(haoyou + "");
                        try {
                            MyPointInfo info = JSON.parseObject(result, MyPointInfo.class);
                            if (info == null) {
                                return;
                            }

                            if (info.getCode() != 200) {
                                ToastUtils.getInstance().showShortToast(info.getMsg());
                                return;
                            }
                            //待返
                            daifan = info.getData().getWill_point();
                            //积分明细
                            jifenmingxi = info.getData().getHad_point();
                            //好友
                            haoyou = info.getData().getFriends_count();

                            tvJfnum.setText(jifenmingxi + "");
                            tvDfnum.setText(daifan + "");
                            tvHynum.setText(haoyou + "");

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private ZCodeDialog mZCodeDialog;

    @OnClick({R.id.img_btn_message, R.id.img_btn_setting, R.id.user_login_info, R.id.user_photo, R.id.tv_allorder, R.id.tv_dfk, R.id.tv_dsh,
            R.id.tv_dpj, R.id.tv_shouhou, R.id.ll_jfmx, R.id.ll_jfdf, R.id.ll_yqhy})
    public void onViewClicked(View view) {
        if(isFastDoubleClick(OtherlastClickTime)){
            return;
        }
        OtherlastClickTime = System.currentTimeMillis();
        int id = view.getId();
        Intent intent = new Intent();
        switch (id) {
            case R.id.img_btn_message:

                break;
            case R.id.img_btn_setting:

                break;
            case R.id.user_login_info: // 登录/注册
                //修改用户信息
                if (UserLoginInfo.isUserLogin()) {
                    intent.setClass(_mActivity, UserInfoEditeActivity.class);
                } else {
                    // 点击跳转登录
                    intent.setClass(_mActivity, LoginActivity.class);
                }
                break;
            case R.id.user_photo: // 登录/注册
                //修改用户信息
                if (UserLoginInfo.isUserLogin()) {
                    intent.setClass(_mActivity, UserInfoEditeActivity.class);
                } else {
                    // 点击跳转登录
                    intent.setClass(_mActivity, LoginActivity.class);
                }
                break;
            case R.id.tv_allorder: // 全部订单
                intent.setClass(_mActivity, MyOrderActivity.class).putExtra("OrderType", 0);
                break;
            case R.id.tv_dfk: // 待付款
                intent.setClass(_mActivity, MyOrderActivity.class).putExtra("OrderType", 1);
                break;
            case R.id.tv_dsh: // 待收货
                intent.setClass(_mActivity, MyOrderActivity.class).putExtra("OrderType", 2);
                break;
            case R.id.tv_dpj: // 待评价
                intent.setClass(_mActivity, MyOrderActivity.class).putExtra("OrderType", 3);
                break;
            case R.id.tv_shouhou: // 售后
                intent.setClass(_mActivity, MyOrderActivity.class).putExtra("OrderType", 4);
                break;
            case R.id.ll_jfmx: // 积分明细
                intent.setClass(_mActivity, IntegralDetailActivity.class);
                break;
            case R.id.ll_jfdf: // 积分待返
                intent.setClass(_mActivity, BackIntegralActivity.class);
                break;
            case R.id.ll_yqhy: // 邀请好友
                intent.setClass(_mActivity, InviteFriendsActivity.class);
                break;
            default:break;
        }
        if (id == R.id.user_login_info) {
            startActivity(intent);
        } else {
            checkLoginAndStartIntent(intent);
        }
    }
    private static long SettinglastClickTime;
    private static long OtherlastClickTime;
    private static boolean isFastDoubleClick(long lastClickTime) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 1000 * 2) {
            return true;
        }
        return false;
    }
}
